package com.qf;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.lang.reflect.Member;
import java.util.List;

/**
 * 作者：铁蛋
 * 时间：2021/10/20 17:16
 * 描述：永无Bug
 */
public class MQConsumer {
    public static void main(String[] args) throws Exception{
//        1.创建消费者Consumer(DefaultMQPushConsumer)，指定消费者组名
        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("test-consumer-group");
//        2.指定Nameserver地址
        consumer.setNamesrvAddr("localhost:9876");
//        3.订阅(subscribe)主题Topic
        consumer.subscribe("testtopic1","testtag1||testtag2");
//        4.设置消费模式(MessageModel),默认集群模式
        consumer.setMessageModel(MessageModel.BROADCASTING);
//        5.注册（register）回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    list.forEach(messageExt -> {
                        System.out.println("topic="+messageExt.getTopic());
                        System.out.println("tag="+messageExt.getTags());
                        System.out.println("body="+ new String(messageExt.getBody()));
                        System.out.println("key="+ messageExt.getKeys());
                    });
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
//        6.启动消费者
        consumer.start();
    }
}
